package org.atlantis.evnlib.execution;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程重命名代理类。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         $Created at: 2012-1-4 下午7:34:40
 */
public class RenamingRunnable implements Runnable {

	private static final Logger log = LoggerFactory.getLogger(RenamingRunnable.class);

	private Runnable runnable;
	private String threadName;

	public RenamingRunnable(Runnable runnable, String threadName) {
		if (runnable == null) throw new NullPointerException("runnable is null.");
		if (threadName == null) throw new NullPointerException("threadName is null.");
		this.runnable = runnable;
		this.threadName = threadName;
	}

	@Override
	public void run() {
		Thread currentThread = Thread.currentThread();
		String oldThreadName = currentThread.getName();
		boolean renamed = false;
		if (!oldThreadName.equals(threadName)) {
			try {
				currentThread.setName(threadName);
				renamed = true;
			} catch (SecurityException e) {
				log.debug("Failed to rename a thread due to security restriction.", e);
			}
		}
		try {
			runnable.run();
		} finally {
			if (renamed) currentThread.setName(oldThreadName);
		}
	}
}
